package pers.fulsun.demo.springcloud.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.fulsun.demo.springcloud.entity.User;
import pers.fulsun.demo.springcloud.helper.RedisHelper;
import pers.fulsun.demo.springcloud.service.UserService;

/**
 * @author fulsun
 * @create: 2021-08-19 15:03
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private UserService userService;
    //引入redis操作工具
    @Autowired
    private RedisHelper redisHelper;

    /**
     * 新增user
     *
     * @param user user对象
     * @return
     */
    @PostMapping
    public boolean addUser(@RequestBody User user) throws JsonProcessingException {
        //填充缓存，key为user_${id}
        return this.redisHelper.set("user_" + user.getId(), new ObjectMapper().writeValueAsString(user));
    }

    /**
     * 根据id获取user
     *
     * @param id user的id
     * @return
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) throws JsonProcessingException {
        //首先从缓存获取
        String s = this.redisHelper.get("user_" + id);
        return new ObjectMapper().readValue(s, User.class);
    }

    /**
     * 根据id删除user
     *
     * @param id user的id
     * @return
     */
    @DeleteMapping("/{id}")
    public void removeUser(@PathVariable Integer id) {
        //从缓存移除
        this.redisHelper.del("user_" + id);
    }

}